﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace GnToolMain
{
    public static class GnTSingleton<T> where T : class
    {
        static volatile T mInstance;
        static readonly object mLock = new object();

        static GnTSingleton()
        {
        }

        public static T Instance
        {
            get
            {
                if (mInstance == null)
                {
                    lock (mLock)
                    {
                        if (mInstance == null)
                        {
                            ConstructorInfo constructor = null;

                            try
                            {
                                // Binding flags exclude public constructors.
                                constructor = typeof(T).GetConstructor(BindingFlags.Instance |
                                    BindingFlags.NonPublic, null, new Type[0], null);
                            }
                            catch (Exception exception)
                            {
                                System.Windows.Forms.MessageBox.Show(exception.Message);
                            }

                            if (constructor == null || constructor.IsAssembly)
                            {
                                System.Windows.Forms.MessageBox.Show(string.Format("A private or " +
                                      "protected constructor is missing for '{0}'.", typeof(T).Name));
                            }
                            mInstance = (T)constructor.Invoke(null);
                        }
                    }
                }
                return mInstance;
            }
        }
    }
}
